package com.afteryuan.util.code;

import java.io.File;
import java.io.IOException;

/**
 * 从领域模型文件创建Service,ServiceImpl,Test等
 * <p><a href="AbstractorGenerator.java.html"><i>View Source</i></a></p>
 *
 * @author <a href="mailto:afteryuan@gmail.com">$Author$</a>
 * @version $Revision$
 */
public abstract class AbstractorGenerator {

    protected String modelFQClassName;//com.afteryuan.model.system.User
    protected String modelClassName;//User
    protected String modelPackageName;//com.afteryuan.model.system
    protected String modelRootPackageName;//com.afteryuan
    protected String modelRootAbsolutePath;// src/java/com/afteryuan/model
    protected Boolean isReplace = false;
    public static final String MODE_SINGLE_PACKAGENAME  = "model";


    /**
     * 构造器
     *
     * @param model   领域模型文件 new File("D:/projects/myproject/src/java/com/afteryuan/model/system/User.java")
     * @param srcRoot 源代码的根目录 new File("D:/project/myproject/src/java")
     */
    protected AbstractorGenerator(File model, File srcRoot) {
        modelClassName = getModelClassName(model);
        modelPackageName = getModelPackageName(model, srcRoot);
        modelRootPackageName = getModelRootPackageName(modelPackageName);
        modelRootAbsolutePath = getModelRootAbsolutePath(model);
        modelFQClassName=modelPackageName+"."+modelClassName;
    }


    /**
     * 创建java文件
     */
    public abstract void generate() throws IOException;

    public Boolean getReplace() {
        return isReplace;
    }

    public void setReplace(Boolean replace) {
        this.isReplace = replace;
    }

    private String getModelClassName(File model) {
        return model.getName().substring(0, model.getName().indexOf(".java"));
    }

    private String getModelPackageName(File model, File srcRoot) {
        String modelPath = model.getPath();
        String srcPath = srcRoot.getPath();
        String modelPackagePath = modelPath.substring(srcPath.length() + 1, modelPath.lastIndexOf(File.separator));
        String modelPackageName = modelPackagePath.replaceAll(getSeperar(), ".");
        return modelPackageName;
    }

    private String getSeperar() {
        if (File.separator.equals("\\")) return "\\\\";
        return File.separator;
    }

    private String getModelRootAbsolutePath(File model) {
        return model.getParent().substring(0,model.getParent().lastIndexOf(File.separator+MODE_SINGLE_PACKAGENAME));
    }

    private String getModelRootPackageName(String modelPackageName) {
        return modelPackageName.substring(0,modelPackageName.lastIndexOf("."+MODE_SINGLE_PACKAGENAME));
    }

}